<template>
  <el-card
    shadow="never"
    class="property-editor"
    v-if="
      activeCell || activeRowForProps !== null || activeColForProps !== null
    "
  >
    <div
      v-if="activeRowForProps !== null && grid && grid.rows[activeRowForProps]"
    >
      <h4>表格属性</h4>
      <el-divider content-position="left"
        >行属性 (行 {{ activeRowForProps + 1 }})</el-divider
      >
      <el-form label-width="100px" size="small">
        <el-form-item label="行高 (px)">
          <el-slider
            :key="`row-height-slider-${activeRowForProps}`"
            :model-value="grid.rows[activeRowForProps].height"
            @update:modelValue="(val: number) => handleRowHeightChange(activeRowForProps!, val)"
            :min="10"
            :max="300"
            show-input
            :step="1"
          />
        </el-form-item>
      </el-form>
    </div>
    <div
      v-if="activeColForProps !== null && grid && grid.cols[activeColForProps]"
    >
      <el-divider content-position="left"
        >列属性 (列
        {{ getColumnLabelForEditor(activeColForProps) }})</el-divider
      >
      <el-form label-width="100px" size="small">
        <el-form-item label="列宽 (px)">
          <el-slider
            :key="`col-width-slider-${activeColForProps}`"
            :model-value="grid.cols[activeColForProps].width"
            @update:modelValue="(val: number) => handleColWidthChange(activeColForProps!, val)"
            :min="20"
            :max="500"
            show-input
            :step="1"
          />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="activeCell">
      <h4>
        单元格属性 ({{ activeCell.rowIndex }},
        {{ getColumnLabelForEditor(activeCell.colIndex) }})
      </h4>
      <el-form label-width="100px" size="small">
        <el-divider content-position="left">样式</el-divider>
        <el-form-item label="背景色">
          <el-color-picker
            :model-value="activeCell.style.backgroundColor"
            @update:modelValue="
              (val) =>
                emit('update-cell-style', {
                  prop: 'backgroundColor',
                  value: val,
                })
            "
            show-alpha
          />
        </el-form-item>
        <el-form-item label="文字颜色">
          <el-color-picker
            :model-value="activeCell.style.color"
            @update:modelValue="
              (val) => emit('update-cell-style', { prop: 'color', value: val })
            "
          />
        </el-form-item>
        <el-form-item label="字号">
          <el-input
            :model-value="activeCell.style.fontSize"
            @update:modelValue="
              (val) =>
                emit('update-cell-style', { prop: 'fontSize', value: val })
            "
            placeholder="e.g., 14px"
          />
        </el-form-item>
        <el-form-item label="文本对齐">
          <el-select
            :model-value="activeCell.style.textAlign"
            @update:modelValue="
              (val) =>
                emit('update-cell-style', { prop: 'textAlign', value: val })
            "
            placeholder="选择对齐方式"
          >
            <el-option label="左对齐" value="left" />
            <el-option label="居中对齐" value="center" />
            <el-option label="右对齐" value="right" />
          </el-select>
        </el-form-item>
        <el-form-item label="垂直对齐">
          <el-select
            :model-value="activeCell.style.verticalAlign"
            @update:modelValue="
              (val) =>
                emit('update-cell-style', { prop: 'verticalAlign', value: val })
            "
            placeholder="选择对齐方式"
          >
            <el-option label="顶部对齐" value="top" />
            <el-option label="垂直居中" value="middle" />
            <el-option label="底部对齐" value="bottom" />
          </el-select>
        </el-form-item>

        <el-divider content-position="left">内容</el-divider>
        <el-form-item label="内容类型">
          <el-select
            v-model="currentContentTypeOnEditor"
            @change="onContentTypeChange"
            placeholder="选择内容类型"
          >
            <el-option label="文本" value="text" />
            <el-option label="输入框" value="input" />
            <el-option label="图片" value="image" />
            <!-- Add more content types here -->
          </el-select>
        </el-form-item>

        <!-- Text Content Properties -->
        <template v-if="activeCell.content?.type === 'text'">
          <el-form-item label="文本来源">
            <el-select
              :model-value="(activeCell.content as TextContent).valueType"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'valueType',
                    value: val,
                  })
              "
            >
              <el-option label="静态文本" value="static" />
              <el-option label="数据元模型" value="metaModel" />
              <el-option label="预定义" value="predefined" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="(activeCell.content as TextContent).valueType === 'static'"
            label="静态内容"
          >
            <el-input
              :model-value="(activeCell.content as TextContent).staticText"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'staticText',
                    value: val,
                  })
              "
              type="textarea"
              :rows="2"
            />
          </el-form-item>
          <el-form-item
            v-if="(activeCell.content as TextContent).valueType === 'metaModel'"
            label="元模型字段"
          >
            <el-select
              :model-value="activeCell.dataMetaModelField"
              @update:modelValue="
                (val) => emit('update-cell-data-field', { field: val })
              "
              placeholder="选择字段"
              clearable
              filterable
            >
              <el-option
                v-for="field in dataMetaModel?.fields"
                :key="field.field"
                :label="`${field.name} (${field.field})`"
                :value="field.field"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="(activeCell.content as TextContent).valueType === 'predefined'"
            label="预定义类型"
          >
            <el-select
              :model-value="(activeCell.content as TextContent).predefinedType"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'predefinedType',
                    value: val,
                  })
              "
            >
              <el-option label="当前日期" value="currentDate" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="(activeCell.content as TextContent).predefinedType === 'currentDate'"
            label="日期格式"
          >
            <el-input
              :model-value="(activeCell.content as TextContent).dateFormat"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'dateFormat',
                    value: val,
                  })
              "
              placeholder="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </template>

        <!-- Input Content Properties -->
        <template v-if="activeCell.content?.type === 'input'">
          <el-form-item label="绑定属性(prop)">
            <el-input
              :model-value="(activeCell.content as InputContent).prop"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', { prop: 'prop', value: val })
              "
              placeholder="表单数据字段名"
            />
          </el-form-item>
          <el-form-item label="输入框类型">
            <el-select
              :model-value="(activeCell.content as InputContent).inputType"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'inputType',
                    value: val,
                  })
              "
            >
              <el-option label="文本" value="text" />
              <el-option label="数字" value="number" />
              <el-option label="日期" value="date" />
              <el-option label="密码" value="password" />
              <el-option label="文本域" value="textarea" />
            </el-select>
          </el-form-item>
          <el-form-item label="绑定元模型">
            <el-select
              :model-value="activeCell.dataMetaModelField"
              @update:modelValue="
                (val) => {
                  emit('update-cell-data-field', { field: val });
                  onMetaFieldForInputChange(val);
                }
              "
              placeholder="选择字段自动填充prop"
              clearable
              filterable
              @change="onMetaFieldForInputChange"
            >
              <el-option
                v-for="field in dataMetaModel?.fields"
                :key="field.field"
                :label="`${field.name} (${field.field})`"
                :value="field.field"
              />
            </el-select>
            <div
              class="el-form-item__description"
              v-if="activeCell.dataMetaModelField"
            >
              (将用于数据回显和可能的默认值)
            </div>
          </el-form-item>
          <el-form-item label="占位符">
            <el-input
              :model-value="(activeCell.content as InputContent).placeholder"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'placeholder',
                    value: val,
                  })
              "
            />
          </el-form-item>
          <el-form-item label="默认值">
            <el-input
              :model-value="(activeCell.content as InputContent).defaultValue"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'defaultValue',
                    value: val,
                  })
              "
            />
          </el-form-item>
          <el-form-item label="禁用">
            <el-switch
              :model-value="(activeCell.content as InputContent).disabled"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'disabled',
                    value: val,
                  })
              "
            />
          </el-form-item>
          <el-form-item label="只读">
            <el-switch
              :model-value="(activeCell.content as InputContent).readonly"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'readonly',
                    value: val,
                  })
              "
            />
          </el-form-item>
          <el-form-item label="必填">
            <el-switch
              :model-value="(activeCell.content as InputContent).required"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'required',
                    value: val,
                  })
              "
            />
          </el-form-item>
        </template>

        <template v-if="activeCell.content?.type === 'image'">
          <el-form-item label="图片来源">
            <el-select
              :model-value="(activeCell.content as ImageContent).srcType"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'srcType',
                    value: val,
                  })
              "
            >
              <el-option label="静态URL" value="staticUrl" />
              <el-option label="数据元模型" value="metaModel" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="(activeCell.content as ImageContent).srcType === 'staticUrl'"
            label="图片URL"
          >
            <el-input
              :model-value="(activeCell.content as ImageContent).staticUrl"
              @update:modelValue="
                (val) =>
                  emit('update-cell-content-prop', {
                    prop: 'staticUrl',
                    value: val,
                  })
              "
              placeholder="http://..."
            />
          </el-form-item>
          <el-form-item
            v-if="(activeCell.content as ImageContent).srcType === 'metaModel'"
            label="元模型字段"
          >
            <el-select
              :model-value="activeCell.dataMetaModelField"
              @update:modelValue="
                (val) => emit('update-cell-data-field', { field: val })
              "
              placeholder="选择图片URL字段"
              clearable
              filterable
            >
              <el-option
                v-for="field in dataMetaModel?.fields"
                :key="field.field"
                :label="`${field.name} (${field.field})`"
                :value="field.field"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { PropType, ref, watch } from 'vue';
import { CellDefinition } from '@/models/cell.model';
import { GridDefinition } from '@/models/grid.model';
import { DataMetaModel } from '@/models/meta-model.model';
import {
  ContentDefinition,
  TextContent,
  InputContent,
  ImageContent,
} from '@/models/content.model';
import { ElMessage } from 'element-plus';

const props = defineProps({
  activeCell: {
    type: Object as PropType<CellDefinition | null>,
    default: null,
  },
  activeRowForProps: { type: Number as PropType<number | null>, default: null },
  activeColForProps: { type: Number as PropType<number | null>, default: null },
  grid: { type: Object as PropType<GridDefinition | null>, default: null },
  dataMetaModel: {
    type: Object as PropType<DataMetaModel | undefined>,
    default: undefined,
  },
});

const emit = defineEmits<{
  (
    e: 'update-cell-content',
    cellDef: CellDefinition,
    newContent: ContentDefinition
  ): void;
  (
    e: 'update-cell-style',
    payload: {
      prop: keyof CellDefinition['style'];
      value: CellDefinition['style'][keyof CellDefinition['style']];
    }
  ): void;
  (e: 'update-cell-data-field', payload: { field: string | null }): void;
  (
    e: 'update-cell-content-prop',
    payload: {
      prop: keyof ContentDefinition;
      value: ContentDefinition[keyof ContentDefinition];
    }
  ): void;
  (
    e: 'update-row-prop',
    payload: { rowIndex: number; propName: 'height'; value: number }
  ): void;
  (
    e: 'update-col-prop',
    payload: { colIndex: number; propName: 'width'; value: number }
  ): void;
}>();

// currentContentTypeOnEditor to avoid direct mutation of computed prop if el-select is strange with it
const currentContentTypeOnEditor = ref<string>('');

watch(
  () => props.activeCell?.content?.type,
  (newType) => {
    currentContentTypeOnEditor.value = newType || '';
  },
  { immediate: true }
);

function onContentTypeChange(newTypeString: string | number | boolean): void {
  // el-select passes string
  const newType = newTypeString as string;
  if (!props.activeCell || props.activeCell.content?.type === newType) return;

  let newContent: ContentDefinition;
  const currentDataMetaModelField = props.activeCell.dataMetaModelField; // Preserve if exists

  switch (newType) {
    case 'text':
      newContent = new TextContent({ staticText: '' });
      break;
    case 'input':
      newContent = new InputContent({
        prop:
          currentDataMetaModelField ||
          `input_${props.activeCell.rowIndex}_${props.activeCell.colIndex}`,
      });
      break;
    case 'image':
      newContent = new ImageContent();
      break;
    default:
      ElMessage.warn(`未知内容类型: ${newType}`);
      newContent = new TextContent({ staticText: '错误:未知类型' }); // Fallback
  }
  // Re-assign dataMetaModelField if it was present, as new ContentDefinition won't have it.
  // The CellDefinition itself holds this.
  emit('update-cell-content', props.activeCell, newContent);
  // activeCell.dataMetaModelField might need to be explicitly set if `newContent` construction wiped it conceptually.
  // However, dataMetaModelField is on CellDefinition, not ContentDefinition, so it should be fine.
}

function onMetaFieldForInputChange(selectedField: string): void {
  if (props.activeCell && props.activeCell.content?.type === 'input') {
    const inputContent = props.activeCell.content as InputContent;
    if (!inputContent.prop || inputContent.prop.startsWith('input_')) {
      // If no prop or default prop
      emit('update-cell-content-prop', { prop: 'prop', value: selectedField });
    } else if (inputContent.prop !== selectedField) {
      if (
        window.confirm(
          `输入框已有关联属性 "${inputContent.prop}"，是否用元模型字段 "${selectedField}" 覆盖它？`
        )
      ) {
        emit('update-cell-content-prop', {
          prop: 'prop',
          value: selectedField,
        });
      } else {
        // User cancelled, revert select if possible or re-set dataMetaModelField to old value
        // This part is tricky with el-select, for now, we assume they commit to the change
        // or the dataMetaModelField on cellDefinition remains the true source of binding.
      }
    }
  }
}

function handleRowHeightChange(rowIndex: number, value: number): void {
  emit('update-row-prop', { rowIndex, propName: 'height', value });
}
function handleColWidthChange(colIndex: number, value: number): void {
  emit('update-col-prop', { colIndex, propName: 'width', value });
}

function getColumnLabelForEditor(colIndex: number | null): string {
  if (colIndex === null) return '';
  let label = '';
  let num = colIndex + 1;
  while (num > 0) {
    const remainder = (num - 1) % 26;
    label = String.fromCharCode(65 + remainder) + label;
    num = Math.floor((num - 1) / 26);
  }
  return label;
}
</script>

<style lang="scss" scoped>
.property-editor {
  padding: 15px;
  height: 100%;
  overflow-y: auto;
  .el-form-item {
    margin-bottom: 14px;
  }
  .el-divider {
    margin: 20px 0;
    font-size: 14px;
  }
  h4 {
    margin-top: 0;
    margin-bottom: 15px;
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }
  .el-form-item__description {
    font-size: 12px;
    color: #909399;
    line-height: 1.5;
    margin-top: 2px;
  }
}
</style>
